# -*-coding: utf-8 -*-
# by zw on 2017/12/27

import logging

from sanic import response
import hashlib
from utils.mongo import get_user_collection, get_usergroup_collection
from sanic import Blueprint
from appconfigsvr.auth.permission import permission_check, PERMISSION

bp = Blueprint('group', url_prefix='/user')
_logger = logging.getLogger(__name__)


@bp.post('/usergroup')
@permission_check(PERMISSION.system)
async def add_usergroup(request):
    try:
        _json = request.json
        groupname = _json["groupname"]
        group = _json["group"]
        permission = _json["permission"]
        get_usergroup_collection().find_one_and_update({"group": group},
                                                             {"$set": _json},
                                                             upsert=True)
        return response.json({"code": 0, "message": "", "data": {}})
    except Exception as e:
        _logger.exception(e)
        return response.json({"code": 4003, "message": "error message %s" % e, "data": {}})


@bp.get('/group_list')
@permission_check(PERMISSION.system)
async def group_list(request):
    try:
        page = int(request.raw_args.get("page", 1))
        limit = int(request.raw_args.get("limit", 30))
        cur = get_usergroup_collection().find({}, {"_id": 0})
        _count= cur.count()

        cur.skip((page - 1) * limit).limit(limit)
        res = []
        for doc in cur:
            res.append(doc)

        return response.json(
            {"code": 0, "message": "", "data": res, "count": _count})

    except Exception as e:
        _logger.exception(e)
        return response.json({"code": 4003, "message": "error message %s" % e, "data": {}})
